package net.mysoft.budgetsoft.system.security;

import java.util.Collection;
import java.util.Iterator;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

/**
 * 
 *
 * Description: 访问决策器，决定某个用户具有的角色，是否有足够的权限去访问某个资源 ;做最终的访问控制决定
 *
 * @author kangrui
 * @version 1.0
 * <pre>
 * Modification History: 
 * Date         Author      Version     Description 
 * ------------------------------------------------------------------ 
 * 2013-12-19    kangrui       1.0        1.0 Version 
 * </pre>
 */
@Component("securityAccessManager")
public class SecurityAccessManagerImpl implements AccessDecisionManager {

	/**
	 * 认证用户是否具有权限访问该url地址
	 * @param auth
	 * @param obj
	 * @param attributes
	 * @throws AccessDeniedException
	 * @throws InsufficientAuthenticationException
	 */
	@Override
	public void decide(Authentication auth, Object obj,
			Collection<ConfigAttribute> attributes) throws AccessDeniedException,
			InsufficientAuthenticationException {
		System.out.println("MyAccessDescisionManager.decide()------------------验证用户是否具有一定的权限--------");  
        if(attributes==null) return;  
        Iterator<ConfigAttribute> it = attributes.iterator();  
        while(it.hasNext()){  
            String needRole = it.next().getAttribute();  
            //authentication.getAuthorities()  用户所有的权限  
            for(GrantedAuthority ga:auth.getAuthorities()){  
                if(needRole.equals(ga.getAuthority())){  
                    return;  
                }  
            }  
        }  
        throw new AccessDeniedException("--------MyAccessDescisionManager：decide-------权限认证失败！"); 
	}

	@Override
	public boolean supports(ConfigAttribute attribute) {
		System.out.println("MyAccessDescisionManager.supports()------------角色名："+attribute.getAttribute());
		return true;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		System.out.println("MyAccessDescisionManager.supports()--------------------------------");
		return true;
	}

}
